package com.netty.pro.netty.inbound_outbound;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author xuzn
 * @ClassName: InoutclientHandler
 * @ProjectName netty-pro
 * @date 2020/3/20/9:22
 */
public class InoutclientHandler extends SimpleChannelInboundHandler<Long> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
    System.out.println("从客户端" + ctx.channel().remoteAddress() + "读取的数据" + msg);
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channelActive + 客户端发送信息");
    ctx.writeAndFlush(123456L);
    /**
     * MyLongToByteEncoder 的父类是MessageToByteEncoder
     * 父类MessageToByteEncoder中有一个write方法
     * if (acceptOutboundMessage(msg)) {
     *  此处的含义:判断当前msg是不是应该处理的类型,如果是处理,如果不是直接跳过encode
     *                 @SuppressWarnings("unchecked")
     *                 I cast = (I) msg;
     *                 buf = allocateBuffer(ctx, cast, preferDirect);
     *                 try {
     *                     encode(ctx, cast, buf);
     *                 } finally {
     *                     ReferenceCountUtil.release(cast);
     *                 }
     *
     *                 if (buf.isReadable()) {
     *                     ctx.write(buf, promise);
     *                 } else {
     *                     buf.release();
     *                     ctx.write(Unpooled.EMPTY_BUFFER, promise);
     *                 }
     *                 buf = null;
     *             } else {
     *                 ctx.write(msg, promise);
     *             }
     */
    // 此处abcdsadfsadfhksdggsddfasdfasdgfdgfghgfhgfh 不会调用 MyLongToByteEncoder 这个handler
    // 因为传入的类型不是long类型
    // 由此可知:我们编写encoder要注意传递的数据类型和要处理的数据类型保持一致
//    ctx.writeAndFlush(Unpooled.copiedBuffer("abcdsadfsadfhksdggsddfasdfasdgfdgfghgfhgfh",CharsetUtil.UTF_8));
  }
}
